package ichubredis

import (
	"gitee.com/ichub/goconfig/common/base/baseconfig"
	"gitee.com/ichub/goconfig/common/base/baseutils"
	"gitee.com/ichub/goconfig/common/base/baseutils/jsonutils"
	"gitee.com/ichub/goconfig/common/base/baseutils/stringutils"
	"github.com/go-redis/redis"
	"time"
)

var RedisInst *IchubRedisClient

const DEFAULT_ExpireTime = time.Second * 60 * 10
const PREKEY_USER = "user::"

type IchubRedisClient struct {
	Client         *redis.Client `json:"-"`
	expire         time.Duration
	redisClientDto *baseconfig.RedisClientDto
}

func (this *IchubRedisClient) RedisClientDto() *baseconfig.RedisClientDto {
	return this.redisClientDto
}

func (this *IchubRedisClient) SetRedisClientDto(redisClientDto *baseconfig.RedisClientDto) {
	this.redisClientDto = redisClientDto
}

func NewIchubRedisClient() *IchubRedisClient {
	return &IchubRedisClient{}
}

func (this *IchubRedisClient) Open() *redis.Client {
	this.Client = redis.NewClient(&redis.Options{
		Addr:     this.redisClientDto.Addr,
		Password: this.redisClientDto.Password,
		DB:       this.redisClientDto.DB,
	})
	return this.Client
}
func (this *IchubRedisClient) GetKeyString(key string) string {

	var v = this.GetKey(key)
	return baseutils.Any2Str(v)

}
func (this *IchubRedisClient) GetKeyInt64(key string) int64 {

	var v = this.GetKey(key)

	return stringutils.Str2Int64(baseutils.Any2Str(v))
}

func (this *IchubRedisClient) GetKeyInt32(key string) int32 {

	var v = this.GetKey(key)
	return stringutils.Str2Int32(baseutils.Any2Str(v))
}
func (this *IchubRedisClient) Get(key string, out any) {
	var result = this.Client.Get(PREKEY_USER + key).Val()
	jsonutils.FromJson(result, out)

}
func (this *IchubRedisClient) Del(key string) {
	this.Client.Del(PREKEY_USER + key)

}

func (this *IchubRedisClient) Set(key string, In any) {
	this.SetKey(key, jsonutils.ToJsonStr(In))
}

func (this *IchubRedisClient) GetKey(key string) any {
	return this.Client.Get(PREKEY_USER + key).Val()
}

func (this *IchubRedisClient) SetKeyTimeout(key string, value any, timeout time.Duration) *redis.Client {
	this.Client.Set(PREKEY_USER+key, value, timeout)
	return this.Client
}

func (this *IchubRedisClient) SetKey(key string, value any) *redis.Client {

	return this.SetKeyTimeout(key, value, DEFAULT_ExpireTime)
}

func (this *IchubRedisClient) SetKeyInt64(key string, value int64) *redis.Client {

	return this.SetKey(key, value)
}

func (this *IchubRedisClient) SetKeyInt32(key string, value int32) *redis.Client {

	return this.SetKey(key, value)
}
